package com.freedom.auth.domain.service.member;

import com.freedom.auth.infrastructure.enums.AuthenticationIdentityEnum;
import com.freedom.common.core.enums.ums.MemberStatusEnum;
import com.freedom.ums.api.member.pojo.dto.MemberAuthDTO;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;


/**
 * 用户认证信息
 *
 */
@Data
public class MemberUserDetails implements UserDetails {

    private Integer memberId;

    private String account;

    private Boolean enabled;

    private Integer storeId;

    /**
     * 扩展字段：认证身份标识，枚举值如下：
     *
     * @see com.freedom.auth.infrastructure.enums.AuthenticationIdentityEnum
     */
    private String authenticationIdentity;

    public MemberUserDetails(MemberAuthDTO member, AuthenticationIdentityEnum authenticationIdentityEnum) {
        this.setMemberId(member.getId());
        if (AuthenticationIdentityEnum.MOBILE.equals(authenticationIdentityEnum)) {
            this.account = member.getMobile();
        }
        if (AuthenticationIdentityEnum.OPENID.equals(authenticationIdentityEnum)) {
            this.account = member.getOpenId();
        }
        if (AuthenticationIdentityEnum.EMAIL.equals(authenticationIdentityEnum)) {
            this.account = member.getEmail();
        }
        if (member.getHaveStore()) {
            this.setStoreId(member.getStoreId());
        }
        this.setEnabled(MemberStatusEnum.NORMAL.getValue().equals(member.getStatus()));
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return new HashSet<>();
    }

    @Override
    public String getPassword() {
        return null;
    }

    @Override
    public String getUsername() {
        return this.account;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
